package com.fei.myback.common;

import com.alibaba.fastjson.JSON;
import com.fei.myback.entity.LoginUser;
import com.fei.myback.utils.JwtTokenUtil;
import com.fei.myback.utils.ResoultType;
import com.fei.myback.utils.ResultEnum;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功
 */
@Component
@Slf4j
public class SuccessLogin implements AuthenticationSuccessHandler {
    //token失效时间
    @Value("${jwt.Expiration}")
    public long outTime;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        /**
         * 因为TestServiceImpl实现了userdetails，并重写了loadUserByUsername，所以在TestServiceImpl中的判定结果会自动返回UserDetails给security，
         * Authentication 再从这个接口就可以获取登录用户的信息，用于生成token
         */
        LoginUser userDetails = (LoginUser) authentication.getPrincipal();
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("username", userDetails.getUsername());
        claims.put("startTime", System.currentTimeMillis());
        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), claims, outTime);
        response.setContentType(ResultEnum.resoultContentType);
        response.getWriter().write(JSON.toJSONString(ResoultType.result(ResultEnum.USER_LOGIN_SUCCESS, jwtToken, true)));
    }
}
